<?php
/**
 * Simple Machines Forum (SMF)
 *
 * @package SMF
 * @author Simple Machines http://www.simplemachines.org
 * @copyright 2011 Simple Machines
 * @license http://www.simplemachines.org/about/smf/license.php BSD
 *
 * @version 2.0
 */

if (!defined('SMF'))
	die('Hacking attempt...');
	
	class db_connect
	{
		private $con;
		private $error;
		private $db_p;
		
		public function __construct($host=null, $db_name=null, $user=null, $password=null, $db_p)
		{
			try
			{
				$db = new PDO('mysql:host='.$host.';dbname='.$db_name, $user, $password);
				$this->con = $db;
			}
			catch(PDOException $e)
			{
				$this->error = 1;
			}
			
			$this->db_p = $db_p;
		}
		
		// Get multiple rows from the database.
		public function getall($sql=null, $params=null)
		{
			if ($this->error != 1)
			{				
				if ($sql != null && $params != null)
				{
					$sql = str_replace('{db_prefix}', $this->db_p, $sql);
					$stmt = $this->con->prepare($sql);
					
					$param_number = 1;
					foreach ($params as $param)
					{
						if (is_string($param))
							$stmt->bindparam($param_number, $param, PDO::PARAM_STR);
						elseif (is_int($param))
							$stmt->bindparam($param_number, $param, PDO::PARAM_INT);
						else
							return false;
							
						$param_number++;
					}
				}
				
				$stmt->execute();
				$result = $stmt->fetchall();
				$stmt->closecursor();
				
				return $result;
			}
			
			return false;
		}
		
		// Get one specific row.
		public function getone($sql, $params=null)
		{
			if ($this->error != 1)
			{				
				if ($sql != null && $params != null)
				{
					$sql = str_replace('{db_prefix}', $this->db_p, $sql);
					$stmt = $this->con->prepare($sql);
				
					$param_number = 1;
					foreach ($params as $param)
					{
						if (is_string($param))
							$stmt->bindparam($param_number, $param, PDO::PARAM_STR);
						elseif (is_int($param))
							$stmt->bindparam($param_number, $param, PDO::PARAM_INT);
						else
							return false;
							
						$param_number++;
					}
				}
				
				$stmt->execute();
				$result = $stmt->fetch();
				$stmt->closecursor();
				
				return $result;
			}
			
			return false;
		}
		
		// Preform an action (update, delete, truncate, create)
		public function action($sql, $params=null)
		{
			if ($this->error != 1)
			{			
				if ($sql != null && $params != null)
				{
					$sql = str_replace('{db_prefix}', $this->db_p, $sql);
					$stmt = $this->con->prepare($sql);
					
					$param_number = 1;
					foreach ($params as $param)
					{
						if (is_string($param))
							$stmt->bindparam($param_number, $param, PDO::PARAM_STR);
						elseif (is_int($param))
							$stmt->bindparam($param_number, $param, PDO::PARAM_INT);
						else
							return false;
							
						$param_number++;
					}
				}
				
				$stmt->execute();
				$stmt->closecursor();
				
				return true;
			}
			
			return false;
		}
	}
?>